package net.kts.attraction.subway.positon;

import java.util.ArrayList;
import java.util.List;

import net.kts.attraction.subway.positon.model.SubwayPosition;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;

public class SubwayPositionDaoSQLite extends SQLiteOpenHelper {

	public SubwayPositionDaoSQLite(Context context, String name,
			CursorFactory factory, int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
	
	
	public List<SubwayPosition> getlocationList(Location location, double searchDis) {
		
		List<SubwayPosition> subPosiList = null;
		SubwayPosition subwayPosition = null;
		double searchDistance = searchDis;
		
		if(searchDistance < 0) {
			searchDistance = 0.01;
//			searchDistance = 0.02;
		}
		
		String sql = "";
		sql += " select * from TBL_STATION_POSTION ";
		sql += " where ";
		sql += " LATITUDE < " + (location.getLatitude() + searchDistance);          
		sql += " AND LATITUDE > " + (location.getLatitude() - searchDistance);
		sql += " AND LONGITUDE < " + (location.getLongitude() +searchDistance);
		sql += " AND LONGITUDE > " + (location.getLongitude() - searchDistance);
		
		
		
		Cursor cursor = getReadableDatabase().rawQuery(sql, null);
		
		cursor.moveToFirst();
		
		int lineNum = 0;
		int stationCode = 0;
		double latitude = 0;
		double longitude = 0;
		
		while(!cursor.isAfterLast()) {
			
			if(subPosiList == null) {
				subPosiList = new ArrayList<SubwayPosition>();
			}
			
			lineNum = cursor.getInt(0);
			stationCode = cursor.getInt(1);
			latitude = cursor.getDouble(2);
			longitude = cursor.getDouble(3);
			
			subwayPosition = new SubwayPosition(String.valueOf(stationCode));
			
			subwayPosition.setLineNum(lineNum);
			subwayPosition.setStationCode(stationCode);
			subwayPosition.setLatitude(latitude);
			subwayPosition.setLongitude(longitude);
			
			
			
			subPosiList.add(subwayPosition);
			
			cursor.moveToNext();
		}
		
		
		return subPosiList;
	}
	
}
